import os
import argparse
import logging
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

# 设置控制台编码为GBK
os.system("chcp 936")

# 配置日志
def setup_logging(log_file="ftp_server.log"):
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s - %(levelname)s - %(message)s",
        handlers=[
            logging.FileHandler(log_file, encoding="gbk"),  # 日志文件
            logging.StreamHandler()  # 控制台输出
        ]
    )

# 创建自定义FTP处理器
class CustomFTPHandler(FTPHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.encoding = "utf-8"  # 设置编码为utf-8

    def on_connect(self):
        logging.info(f"客户端连接: {self.remote_ip}:{self.remote_port}")

    def on_disconnect(self):
        logging.info(f"客户端断开连接: {self.remote_ip}:{self.remote_port}")

    def on_login(self, username):
        logging.info(f"用户登录: {username} ({self.remote_ip}:{self.remote_port})")

    def on_logout(self, username):
        logging.info(f"用户登出: {username} ({self.remote_ip}:{self.remote_port})")

    def on_file_sent(self, file):
        logging.info(f"文件发送完成: {file} ({self.remote_ip}:{self.remote_port})")

    def on_file_received(self, file):
        logging.info(f"文件接收完成: {file} ({self.remote_ip}:{self.remote_port})")

    def on_incomplete_file_sent(self, file):
        logging.info(f"文件发送未完成: {file} ({self.remote_ip}:{self.remote_port})")

    def on_incomplete_file_received(self, file):
        logging.info(f"文件接收未完成: {file} ({self.remote_ip}:{self.remote_port})")

    def on_delete(self, file):
        logging.info(f"文件删除: {file} ({self.remote_ip}:{self.remote_port})")

    def on_rename(self, from_name, to_name):
        logging.info(f"文件重命名: {from_name} -> {to_name} ({self.remote_ip}:{self.remote_port})")

    def on_file_modified(self, file):
        logging.info(f"文件修改: {file} ({self.remote_ip}:{self.remote_port})")

    def on_command(self, cmd, arg):
        logging.info(f"客户端命令: {cmd} {arg} ({self.remote_ip}:{self.remote_port})")

    def handle_exception(self, request, client_address):
        logging.error(f"异常发生: {request} {client_address}", exc_info=True)

# 创建FTP服务器
def create_ftp_server(
    shared_dir=None,
    username="guest",
    password="",
    port=21,
    max_cons=100,
    max_cons_per_ip=10
):
    try:
        # 如果未提供共享目录，默认为当前目录
        if shared_dir is None:
            shared_dir = os.getcwd()

        # 检查共享目录是否存在
        if not os.path.exists(shared_dir):
            raise ValueError(f"共享目录 {shared_dir} 不存在")

        # 创建授权器并添加用户
        authorizer = DummyAuthorizer()
        authorizer.add_user(username, password, shared_dir, perm="elradfmw")

        # 创建自定义处理器并绑定授权器
        handler = CustomFTPHandler
        handler.authorizer = authorizer

        # 设置最大并发连接数
        handler.max_concurrent_connections = max_cons
        handler.max_cons_per_ip = max_cons_per_ip

        # 启用TCP_NODELAY
        handler.tcp_no_delay = True

        # 创建并启动服务器
        server = FTPServer(("0.0.0.0", port), handler)
        logging.info(f"FTP 服务器已启动，监听端口 {port}，共享目录为 {shared_dir}")
        logging.info(f"最大并发连接数: {max_cons}")
        logging.info(f"每个IP的最大并发连接数: {max_cons_per_ip}")
        logging.info("TCP_NODELAY 已启用")
        server.serve_forever()
    except Exception as e:
        logging.error(f"服务器启动失败: {e}", exc_info=True)

if __name__ == "__main__":
    # 配置日志
    setup_logging()

    # 创建命令行参数解析器
    parser = argparse.ArgumentParser(description="启动一个FTP服务器")
    parser.add_argument(
        "-s", "--shared_directory",
        type=str,
        help="共享目录路径 (默认: 当前目录)",
        default=None
    )
    parser.add_argument(
        "-u", "--ftp_username",
        type=str,
        help="FTP用户名 (默认: guest)",
        default="guest"
    )
    parser.add_argument(
        "-p", "--ftp_password",
        type=str,
        help="FTP密码 (默认: 空)",
        default=""
    )
    parser.add_argument(
        "-port", "--ftp_port",
        type=int,
        help="FTP服务器端口 (默认: 21)",
        default=21
    )
    parser.add_argument(
        "--max_cons",
        type=int,
        default=500,
        help="最大并发连接数 (默认: 500)"
    )
    parser.add_argument(
        "--max_cons_per_ip",
        type=int,
        default=50,
        help="每个IP的最大并发连接数 (默认: 50)"
    )

    # 解析命令行参数
    args = parser.parse_args()

    # 调用函数启动FTP服务器
    create_ftp_server(
        args.shared_directory,
        args.ftp_username,
        args.ftp_password,
        args.ftp_port,
        max_cons=args.max_cons,
        max_cons_per_ip=args.max_cons_per_ip
    )